package com.service.business.email;

import com.service.business.base.controller.req.VerifyCodeReq;
import com.service.business.base.enums.NotifyCodeEnum;
import com.service.business.base.enums.VerifyCodeEnum;
import com.service.business.base.service.ConfigService;
import com.service.business.base.service.VerifyCodeService;
import com.service.business.support.Language;
import com.service.business.utils.I18nUtil;
import com.service.dao.constants.ConfigConstants;
import com.service.dao.model.SysConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

/**
 * <dl>
 * <dt>back-end</dt>
 * <dd>Description:</dd>
 * <dd>Copyright: Copyright (C) 2015</dd>
 * <dd>Company: </dd>
 * <dd>CreateDate: 2019年09月18日</dd>
 * </dl>
 *
 * @author
 */
@Slf4j
@Service
public class MailService {

    @Value("${spring.mail.username}")
    private String fromAccount;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private VerifyCodeService verifyCodeService;

    @Autowired
    private ConfigService configService;

    private String querySiteName(){
        SysConfig sysConfig = configService.getConfigByName(ConfigConstants.WEB_SITE_TITLE);
        return sysConfig.getConfValue();
    }

    /**
     * 发送一般验证码消息
     * @param verifyCodeReq
     * @param verifyCode
     */
    public void sendCodeTplEmail(VerifyCodeReq verifyCodeReq, String verifyCode){
        sendEmail(verifyCodeReq,verifyCode,buildCodeInHelper());
    }


    public void sendTplEmail(VerifyCodeReq verifyCodeReq, String verifyCode){
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            HashMap<String,String> langmail = buildInHelper();
            helper.setTo(verifyCodeReq.getAccount());
            //设置自定义发件人昵称
            String nick="";
            try {
                nick=javax.mail.internet.MimeUtility.encodeText(querySiteName());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            helper.setFrom(nick+" <"+fromAccount+">");
            helper.setSubject(langmail.get("subject"));
            Context ctx = new Context();
            ctx.setVariable("title", langmail.get("title"));
            ctx.setVariable("verifyCode", verifyCode);
            ctx.setVariable("message", langmail.get("message"));
            ctx.setVariable("info", langmail.get("info"));
            String mail = templateEngine.process("email.html", ctx);
            helper.setText(mail, true);
            javaMailSender.send(message);
            verifyCodeService.insertSendVerifyCodeRecord(verifyCodeReq, verifyCode, VerifyCodeEnum.EMAIL);
        } catch (MessagingException e) {
            log.error("{}向{}发送邮件失败", fromAccount, verifyCodeReq.getAccount());
            System.out.println("发送失败");
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
        }
    }

    public void sendNotifyTplEmail(String toEmail, String typeName){
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            HashMap<String,String> langmail = buildNotifyInHelper(typeName);
            helper.setTo(toEmail);
            //设置自定义发件人昵称
            String nick="";
            try {
                nick=javax.mail.internet.MimeUtility.encodeText(querySiteName());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            helper.setFrom(nick+" <"+fromAccount+">");
            helper.setSubject(langmail.get("subject"));
            Context ctx = new Context();
            ctx.setVariable("title", langmail.get("title"));
//            ctx.setVariable("verifyCode", verifyCode);
            ctx.setVariable("message", langmail.get("message"));
            ctx.setVariable("info", langmail.get("info"));
            String mail = templateEngine.process("notify.html", ctx);
            helper.setText(mail, true);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            log.error("{}向{}发送邮件失败", fromAccount, toEmail);
            System.out.println("发送失败");
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
        }
    }


    /**
     * 公共的邮件发送函数
     * @param verifyCodeReq
     * @param verifyCode
     * @param langmail
     */
    private void sendEmail(VerifyCodeReq verifyCodeReq, String verifyCode,HashMap<String,String> langmail){
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(verifyCodeReq.getAccount());
            //设置自定义发件人昵称
            String nick="";
            try {
                nick=javax.mail.internet.MimeUtility.encodeText(querySiteName());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            helper.setFrom(nick+" <"+fromAccount+">");
            helper.setSubject(langmail.get("subject"));
            Context ctx = new Context();
            ctx.setVariable("title", langmail.get("title"));
            ctx.setVariable("verifyCode", verifyCode);
            ctx.setVariable("message", langmail.get("message"));
            ctx.setVariable("info", langmail.get("info"));
            String mail = templateEngine.process("email.html", ctx);
            helper.setText(mail, true);
            javaMailSender.send(message);
            verifyCodeService.insertSendVerifyCodeRecord(verifyCodeReq, verifyCode, VerifyCodeEnum.EMAIL);
        } catch (MessagingException e) {
            log.error("{}向{}发送邮件失败", fromAccount, verifyCodeReq.getAccount());
            System.out.println("发送失败");
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
        }
    }




    //构建多语言
    private HashMap<String,String> buildInHelper(){
        String lang = Language.LANG.get();
        if (StringUtils.isBlank(lang)) {
            lang = I18nUtil.CLocale.zh_CN;
        }
        HashMap<String,String> langMail = new HashMap<String,String>();
        switch (lang){
            case I18nUtil.CLocale.zh_CN:
                langMail.put("title","账号验证");
                langMail.put("message","您正在账号验证，请输入下面6位验证码以完成验证操作。");
                langMail.put("info","欢迎使用"+querySiteName()+"，此邮件是自动发送，请勿回复。");
                langMail.put("subject","账号验证");
                break;
            case I18nUtil.CLocale.zh_TW:
                langMail.put("title","賬號驗證");
                langMail.put("message","您正在號碼驗證，請輸入下面6位數字的驗證碼以完成驗證工作。");
                langMail.put("info","歡迎使用"+querySiteName()+"，此郵件是自動發送郵件，請勿回覆。");
                langMail.put("subject","賬號驗證");
                break;
            case I18nUtil.CLocale.en_US:
                langMail.put("title","Create A New Account");
                langMail.put("message","You are creating account, please enter the 6-digit verification code below to complete the verification.");
                langMail.put("info","Welcome to the "+querySiteName()+". This message is sent automatically. Please do not reply.");
                langMail.put("subject","Verification");
                break;
            case I18nUtil.CLocale.ko_KO:
                langMail.put("title","새 계정 만들기");
                langMail.put("message","\"등록\"중입니다. 아래 6 자리 인증 코드를 입력하여 인증 작업을 완료하십시오.");
                langMail.put("info",querySiteName()+" 에 오신 것을 환영합니다.이 메시지는 자동으로 전송됩니다. 답장을 보내지 마십시오.");
                langMail.put("subject","확인");
                break;
            case I18nUtil.CLocale.ja_JP:
                langMail.put("title","新しいアカウントを作成");
                langMail.put("message","「登録」しています。確認操作を完了するには、以下に6桁の確認コードを入力してください。");
                langMail.put("info",querySiteName()+" へようこそ。このメッセージは自動的に送信されます。返信しないでください。");
                langMail.put("subject","検証アカウント");
                break;
            default:
                langMail.put("title","Create A New Account");
                langMail.put("message","You are creating account, please enter the 6-digit verification code below to complete the verification.");
                langMail.put("info","Welcome to the "+ querySiteName() +". This message is sent automatically. Please do not reply.");
                langMail.put("subject","Verification");
                break;
        }
        return langMail;
    }

    private HashMap<String,String> buildNotifyInHelper(String typeName){
        String lang = Language.LANG.get();
        if (StringUtils.isBlank(lang)) {
            lang = I18nUtil.CLocale.zh_CN;
        }
        HashMap<String,String> langMail = new HashMap<String,String>();
        switch (lang){
            case I18nUtil.CLocale.zh_CN:
                langMail.put("title","系统提示");
                langMail.put("message","您已达到平台"+typeName+"分红资格，请联系客服进行分红资格申请。感谢您的使用！");
                langMail.put("info","欢迎使用"+querySiteName()+"，此邮件是自动发送，请勿回复。");
                langMail.put("subject","系统提示");
                break;
            default:
                langMail.put("title","系统提示");
                langMail.put("message","您已达到平台"+typeName+"分红资格，请联系客服进行分红资格申请。感谢您的使用！");
                langMail.put("info","欢迎使用"+querySiteName()+"，此邮件是自动发送，请勿回复。");
                langMail.put("subject","系统提示");
                break;
        }
        return langMail;
    }



    //构建多语言
    private HashMap<String,String> buildCodeInHelper(){
        String lang = Language.LANG.get();
        if (StringUtils.isBlank(lang)) {
            lang = I18nUtil.CLocale.zh_CN;
        }
        HashMap<String,String> langMail = new HashMap<String,String>();
        switch (lang){
            case I18nUtil.CLocale.zh_CN:
                langMail.put("title",querySiteName());
                langMail.put("message","请输入下面6位验证码以完成验证操作。");
                langMail.put("info","欢迎使用"+querySiteName()+"，此邮件是自动发送，请勿回复。");
                langMail.put("subject","账号验证码");
                break;
            case I18nUtil.CLocale.zh_TW:
                langMail.put("title",querySiteName()+"驗證碼");
                langMail.put("message","請輸入下面6位數字的驗證碼以完成驗證工作。");
                langMail.put("info","歡迎使用"+querySiteName()+"，此郵件是自動發送郵件，請勿回覆。");
                langMail.put("subject","賬號驗證碼");
                break;
            case I18nUtil.CLocale.en_US:
                langMail.put("title",querySiteName()+" Verification");
                langMail.put("message","Please enter the 6-digit verification code below to complete the verification.");
                langMail.put("info","Welcome to the "+querySiteName()+". This message is sent automatically. Please do not reply.");
                langMail.put("subject","Verification");
                break;
            case I18nUtil.CLocale.ko_KO:
                langMail.put("title",querySiteName()+" 인증 코드");
                langMail.put("message","아래 6 자리 인증 코드를 입력하여 인증 작업을 완료하십시오.");
                langMail.put("info",querySiteName()+" 에 오신 것을 환영합니다.이 메시지는 자동으로 전송됩니다. 답장을 보내지 마십시오.");
                langMail.put("subject","확인");
                break;
            case I18nUtil.CLocale.ja_JP:
                langMail.put("title",querySiteName()+" 確認コード");
                langMail.put("message","「確認操作を完了するには、以下に6桁の確認コードを入力してください。");
                langMail.put("info",querySiteName()+ "へようこそ。このメッセージは自動的に送信されます。返信しないでください。");
                langMail.put("subject","検証アカウント");
                break;
            default:
                langMail.put("title",querySiteName()+"Verification");
                langMail.put("message","Please enter the 6-digit verification code below to complete the verification.");
                langMail.put("info","Welcome to the "+querySiteName()+". This message is sent automatically. Please do not reply.");
                langMail.put("subject","Verification");
                break;
        }
        return langMail;
    }

}
